<template>
  <div class="container">
    <div class="body">
      <el-card style="width: 70%;">
        <div style="display:flex;margin: 5px;align-items: center;justify-content: space-between">
          <h3>我的购物车 <span style="margin-left: 50px">总金额{{this.totalPrice.toFixed(2)}}</span>￥</h3>
          <div style="display: flex">
            <div style="display: flex;align-items: center">
                <el-button size="small" slot="reference" type="primary" plain @click="tryBuyTicked">批量结算</el-button>

              <el-popconfirm
                      confirm-button-text='好的'
                      cancel-button-text='不用了'
                      icon="el-icon-info"
                      icon-color="red"
                      title="确定删除全部选中内容？"
                      @confirm="deleteCartOnTick">
                <el-button size="small" slot="reference" type="danger" plain >批量移除</el-button>
              </el-popconfirm>

              <el-checkbox style="margin-left: 10px" label="全部勾选" border size="small" v-model="isAllSelected" @change="selectAll(isAllSelected)"></el-checkbox>
            </div>
          </div>


        </div>
        <el-card v-for="(item,index) in cart" :key="index" class="item_in_cart">
          <div style="display: flex;width: 100%;">
            <div class="image">
              <img v-on:click="toDetail(item.bookId)" v-if="cartNameImage[index]!=undefined" :src="cartNameImage[index][1]" height="150px"/>
            </div>
            <div class="detail">
              <table>
              </table>
              <p v-if="cartNameImage[index]!=undefined">书名：<span>{{cartNameImage[index][0]}}</span></p>
              <!--<el-input-number size="mini" v-model="item.count" :min="1" :max="10"></el-input-number>-->
              <p>数量：
                <el-input size="mini" v-model="item.count" style="width: 150px" disabled>
                  <el-button size="small" slot="prepend" type="primary" @click="deleteinCart(item.bookId,1,item.count)"><i class="el-icon-minus"></i></el-button>
                  <el-button size="small" slot="append" type="primary" @click="addtoCart(item.bookId,1,item.count)"><i class="el-icon-plus"></i></el-button>
                </el-input>
              </p>
              <p>金额：<span>{{(item.count*item.unitPrice).toFixed(2)}}</span></p>
            </div>
            <div class="operation">
              <div>
                <el-button plain size="small" @click="toDetail(item.bookId)">查看商品</el-button>
                  <el-button size="small" @click="tryBuyOne(index)" type="primary" plain>结算</el-button>
                <el-popconfirm
                        confirm-button-text='好的'
                        cancel-button-text='不用了'
                        icon="el-icon-info"
                        icon-color="red"
                        title="确定删除此书籍？"
                        @confirm="deleteinCart(item.bookId,item.count)">
                  <el-button size="small" slot="reference" type="danger" plain >移除</el-button>
                </el-popconfirm>
              </div>

            </div>
            <div class="checkbox">
              <el-checkbox label="选中商品" border size="small" v-model="isSelected[index]" @change="checkSelection"></el-checkbox>
            </div>
          </div>
        </el-card>
      </el-card>
    </div>


    <el-dialog
            title="确认购买"
            :visible.sync="dialogVisible"
            width="30%"
            style="overflow-y: scroll"
            :before-close="handleClose">
      <el-card style="margin: 5px;" body-style="display:flex;" v-for="(item,index) in onBuy" :key="index">
        <div style="width: 30%;cursor: pointer" v-on:click="toDetail(item.bookId)">
          <img v-if="onBuyCartNameIndex[index]!==undefined" :src="onBuyCartNameIndex[index][1]" style="width: 110px">
        </div>
        <div style="width: 70%">
          <div style="height: 120px">
            <p v-if="onBuyCartNameIndex[index]!=undefined" style="font-weight: bolder">{{onBuyCartNameIndex[index][0]}}</p>
            <el-input-number size="small" v-model="item.count" :min="1"></el-input-number>
          </div>
        </div>
      </el-card>
      <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="directPay()">确 定</el-button>
            </span>
    </el-dialog>


  </div>
</template>

<script>
  import axios from 'axios'
export default {
  name: "Cart",
  data(){
    return{
      /*结算函数*/
      onBuyCartNameIndex:[],
      dialogVisible:false,
      onBuy:[],
      onBuyIds:[],
      isAllSelected:false,
      isSelected:[],
      totalPrice:0,
      cart:[],
      cartNameImage:[],
    }
  },
  async mounted() {
    this.initCart()
    },
  methods:{
    tryBuyTicked(){
      this.onBuy=[]
      this.onBuyCartNameIndex=[]
      var j
      for (j=0;j<this.cart.length;j++){
        if(this.isSelected[j]===true){
          this.onBuy.push(this.cart[j])
          this.onBuyCartNameIndex.push(this.cartNameImage[j])
        }
      }
      console.log(this.onBuy)
      if(this.onBuy.length>0){
        this.dialogVisible=true
      }else {
        this.$message.warning("请先选择商品")
      }

    },
    tryBuyOne(index){
      this.onBuy=[]
      this.onBuy.push(this.cart[index])
      this.onBuyCartNameIndex.push(this.cartNameImage[index])
      if(this.onBuy.length>0){
        this.dialogVisible=true
      }else {
        this.$message.warning("请先选择商品")
      }
    },
    handleClose(){
      this.dialogVisible=false
    },
    /*通过数组完成批量选购*/
    async directPay(){
      var onBuyIds=[]
      var j
      for (j=0;j<this.onBuy.length;j++){
          onBuyIds.push(this.onBuy[j].cartId)
      }
      let mydata = {
        cartIds:onBuyIds,
      }
      axios.post('/cart/payWithCart',mydata).then((res)=>{
        console.log(res)
        if (res.data.code===0||res.data.code==200){
          this.$message.success("成功")
          this.getCart()
          this.selectAll(false)
        }
      })
      this.handleClose()
    },
    checkSelection(param){
      if(!param){
        this.isAllSelected=param
      }else {
        var j
        for(j = 0; j < this.cart.length; j++) {
          if(this.isSelected[j] === false){
            this.sum()
            return
          }
        }
        this.isAllSelected=true
      }
      this.sum()
    },
    selectAll(param){
        var j
        for(j = 0; j < this.cart.length; j++) {
          this.isSelected[j] = param
        }
      console.log(this.isSelected)
      this.sum()
    },
    toDetail(param){
      this.$router.push({ path:'/home/bookdetail', query:{ bookId:param } })
    },
    getdetail(){
      this.$router.push({path:'/home/bookdetail'});
    },
    sum(){
      this.totalPrice=0;
      var j;
      for(j = 0; j < this.cart.length; j++) {
        if(this.isSelected[j]===true){
          this.totalPrice+=(this.cart[j].count*this.cart[j].unitPrice)
        }
      }
    },
    addtoCart(bookId,count){
      let mydata = {
        uid:sessionStorage.getItem('userId'),
        count:count,
        bookId:bookId,
      }
      axios.post('/cart/addBook',mydata).then((res)=>{
        console.log(res)
        if (res.data.code === 0 ||res.data.code === 200){
          this.getCart()
        }
      })
    },
    deleteinCart(bookId,count){
      let mydata = {
        uid:sessionStorage.getItem('userId'),
        count:count,
        bookId:bookId,
      }
      axios.post('/cart/delBook',mydata).then((res)=>{
        console.log(res)
        if (res.data.code === 0 ||res.data.code === 200){
          this.getCart()
        }
      })
    },
    async deleteCartOnTick(){
      var j
      for(j = 0; j < this.cart.length; j++) {
        if(this.isSelected[j]===true){
          this.deleteinCart(this.cart[j].bookId,this.cart[j].count)
        }
      }
    },
    async getCart(){
      let mydata = {
        uid:sessionStorage.getItem('userId'),
      }
      axios.post('/cart/search',mydata).then((res)=>{
        console.log(res)
        if (res.data.code === 0 ||res.data.code === 200){
          this.cart=res.data.data

          var internal
          let comData=[]
          for(internal = 0; internal < this.cart.length; internal++) {
            comData[internal]=this.cart[internal].bookId
          }
          mydata={
            "bookIds":comData
          }
          axios.post('/cart/searchN&U',mydata).then((res)=>{
            console.log(res)
            this.cartNameImage=res.data.data
          })
          this.sum()
        }
      })
    },
    //g
    async initCart(){
      let mydata = {
        uid:sessionStorage.getItem('userId'),
      }
      axios.post('/cart/search',mydata).then((res)=>{
        console.log(res)
        if (res.data.code === 0 ||res.data.code === 200){
          this.cart=res.data.data

          var internal
          let comData=[]
          for(internal = 0; internal < this.cart.length; internal++) {
            comData[internal]=this.cart[internal].bookId
          }
          mydata={
            "bookIds":comData
          }
          axios.post('/cart/searchN&U',mydata).then((res)=>{
            console.log(res)
            this.cartNameImage=res.data.data
          })

          this.selectAll(false)
          this.sum()
        }
      })
    }
  }
}
</script>

<style scoped>
  .container{

  }
  .header{
    width: 100%;
    height: 200px;
    background-color: #B3C0D1;
  }
  .body{
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .item_in_cart{
    margin: 5px;
  }
  .image{
    width: 20%;
  }
  .detail{
    width: 80%;
  }
  .operation{
    width: 25%;
  }
  .checkbox{
    height: 100%;
    align-items: center;
  }
</style>
